<?php

namespace app\shop\controller;

use think\Request;
use think\Exception;
use app\shop\model\Order as OrderModel;
use app\shop\model\Cart as CartModel;
use app\shop\model\Address as AddressModel;
use app\shop\model\Invoice as InvoiceModel;
use app\shop\model\OrderGoods as OrderGoodsModel;

class Order extends \PurchaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $orderModel = new OrderModel();

        try {
            $data = $orderModel->where()->order()->select();

            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        $orderModel = new OrderModel();

        try {

            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save()
    {

        $post = input('post.');
        $userId = \request()->header('userId');

        /* @var $validate \ShopValidate */
        $validate = \think\Loader::validate('Order');
        if ( !$validate->scene('')->check($post) ) {
            return $validate->getError();
        }

        $orderModel = new OrderModel();

        try {
            $orderModel->startTrans();

            // 收货地址信息
            $addressModel = new AddressModel();
            $addressInfo = $addressModel->where([
                'addr_id' => $post['addressId'],
                'user_id' => $userId,
            ])->find();

            // 开票信息
            $invoiceModel = new InvoiceModel();
            $invoiceInfo = $invoiceModel->where([
                'invoice_id' => $post['invoiceId'],
                'user_id' => $userId,
            ])->find();

            // 添加订单信息
            $data = [
                'user_id' => $userId,
                'delivery_time' => $post['deliveryDate'],
            ];
            $data['attr_info'] = json_encode($addressInfo);
            $data['invoice_info'] = json_encode($invoiceInfo);

            $result = $orderModel->data($data)->allowField(true)->save();

            // 订单商品信息
            $cartModel = new CartModel();
            $cartGoods = $cartModel->where([
                'user_id' => $userId,
                'unchecked' => 0,
            ])->relation('goods')->select();

            $list = array_map(function($goods) use ($orderModel) {
                return [
                    'order_id' => $orderModel->order_id,
                    'goods_id' => $goods->goods_id,
                    'quantity' => $goods->quantity,
                    'goods_info' => json_encode([
                        'goods_name' => $goods->goods->goods_name,
                        'price' => $goods->goods->price,
                        'stock' => $goods->goods->stock,
                    ]),
                    'subtotal' => $goods->goods->price * $goods->quantity,
                ];
            }, $cartGoods);

            $orderGoodsModel = new OrderGoodsModel();
            $orderGoodsModel->saveAll($list);

            // 附件信息


            // 优惠详情

            // 计算应付金额


            // 删除购物车商品
            $cartModel->where([
                'user_id' => $userId,
                'unchecked' => 0,
            ])->delete();

            $orderModel->commit();

            $this->successTerminate($orderModel);
        } catch (Exception $e) {
            $orderModel->rollback();
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        $orderModel = new OrderModel();

        try {

            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        $orderModel = new OrderModel();

        try {

            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $orderModel = new OrderModel();

        try {

            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $orderModel = new OrderModel();

        try {

            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
}
